/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package IoTools;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.SymbolAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.LookupPaintScale;
import org.jfree.chart.renderer.xy.XYBlockRenderer;
import org.jfree.chart.title.PaintScaleLegend;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.data.xy.XYZDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RectangleInsets;

/**
 *
 * @author godjam
 */
public class AnalyserTools {

    /**
     * JFreeChartBuilder : build addedLines 2Dplot from addedLines dataset
     * @param title : the title
     * @param xaxis : xaxis label
     * @param yaxis : yaxis label
     * @param dataset : the dataset to plot
     * @return addedLines chart
     */
    public static JFreeChart JFreeChartBuilder(String path, String name, String title, String xaxis, String yaxis,
            XYSeriesCollection dataset) throws IOException {
        JFreeChart chart = ChartFactory.createXYLineChart(
                title, //the title
                xaxis, // x axis label
                yaxis, // y axis label
                dataset, // dataset
                PlotOrientation.VERTICAL,
                true, // legend
                true, // tooltips
                false);             // urls

        /* finally export it as png */
        PNGExporter(path, name + "_" + title, chart);

        return chart;
    }

    /**
     *
     * @param path
     * @param name
     * @param title
     * @param xaxis
     * @param yaxis
     * @param dataset
     * @return
     * @throws java.io.IOException
     */
    public static JFreeChart JFCBarBuilder(String path, String name, String title, String xaxis, String yaxis,
            DefaultCategoryDataset dataset) throws IOException {
        JFreeChart spikesChart = ChartFactory.createBarChart(
                title, // chart title
                xaxis, // domain axis label
                yaxis, // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
                );
        PNGExporter(path, name + "_spikes", spikesChart);
        return spikesChart;
    }

    /**
     * 
     * @param path
     * @param name
     * @param title
     * @param xaxis
     * @param yaxis
     * @param dataset
     * @return
     * @throws java.io.IOException
     */
    public static JFreeChart JFCXYBlockBuilder(String path, String name, String title, String xaxis, String yaxis,
            XYZDataset dataset, ParamSet p) {
        System.out.println(name + " dataset series : " + dataset.getSeriesCount());
        System.out.println(name + " dataset series size : " + dataset.getItemCount(0));
        for (int i = 0; i < dataset.getSeriesCount(); i++) {
            for (int j = 0; j < dataset.getItemCount(i);j++) {
                System.out.println("x:" + dataset.getX(i, 0));
                System.out.println("y:" + dataset.getY(i, 0));
                System.out.println("z:" + dataset.getZ(i, 0));
            }
        }
        //JFreeChart chart = ChartFactory.createBubbleChart(name, xaxis, yaxis, dataset, PlotOrientation.HORIZONTAL, true, true, false);

        ///*
        //xaxis
        String[] axe1 = new String[p.GammaLoop()];
        Double k = p.GammaMin();
        for (int i = 0; i < p.GammaLoop(); i++) {
        k += p.GammaStep();
        axe1[i] = prettyFormat(k);
        }
        SymbolAxis xAxis = new SymbolAxis(xaxis, axe1);

        //yaxis
        String[] axe2 = new String[p.DeltaLoop()];
        Double l = p.DeltaMin();
        for (int i = 0; i < p.DeltaLoop(); i++) {
        l += p.DeltaStep();
        axe2[i] = prettyFormat(l);
        }
        SymbolAxis yAxis = new SymbolAxis(yaxis, axe2);
        //yAxis.setInverted(true);
        //zaxis
        NumberAxis scaleAxis = new NumberAxis("Spikes");
        scaleAxis.setRange(0.0, 550.0);
        LookupPaintScale paintScale = new LookupPaintScale(0.0, 550.0, Color.GRAY);
        for(int i=0; i<255; i++){
            paintScale.add((i*2), new Color(254-i,254-i,254-i));
        }
 
        //renderer
        XYBlockRenderer renderer = new XYBlockRenderer();
        renderer.findRangeBounds(dataset);
        renderer.setPaintScale(paintScale);

        //XYplot 
        XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);

        // JFreeChart
        JFreeChart chart = new JFreeChart(title, plot);

        // attach zaxis
        PaintScaleLegend psl = new PaintScaleLegend(paintScale, scaleAxis);
        psl.setPosition(RectangleEdge.RIGHT);
        psl.setMargin(new RectangleInsets(5, 5, 5, 5));
        chart.removeLegend();
        chart.addSubtitle(psl);
        //*/
        //PNGExporter
        try {
            PNGExporter(path, name, chart);
        } catch (IOException ex) {
            Logger.getLogger(AnalyserTools.class.getName()).log(Level.SEVERE, null, ex);
        }
        //*/
        return chart;
    }

    /**
     * PNGExporter
     * Permit to export a chart into a png file
     * @param name
     * @param chart
     * @throws java.io.IOException
     */
    public static void PNGExporter(String path, String name, JFreeChart chart) throws IOException {
        ChartUtilities.saveChartAsPNG(
                new File(path + name + ".png"),
                chart, //the chart
                800, //width
                600, //height
                null, //chart rendering info null:)
                true,//alpha
                9);//compression 1-9
    }

    /**
     * 
     * @param k
     * @return
     */
    public static String prettyFormat(Number k) {
        String masque = new String("#0.###");
        DecimalFormat form = new DecimalFormat(masque); // import java.text.DecimalFormat;
        String rez = form.format(k);
        return rez;
    }
    
    public static Double Round( Double what, int howMuch) {
       return (double)( (int)(what * Math.pow(10,howMuch) + .5) ) / Math.pow(10,howMuch);
    }


    /**
     * computeSolDimension
     * compute the solution dimension : numbers of equations
     * @param String file : url to the file to read
     * @return int :
     */
    public static int computeSolDimension(String file) throws FileNotFoundException, IOException, Exception {
        FileReader r = new FileReader(file);   // initialize reader and
        BufferedReader i0 = new BufferedReader(r);   // buffered reader
        String inputLine = i0.readLine();   // amount of tokens on first line will
        StringTokenizer tokenizer = new StringTokenizer(inputLine, " ");   // be one less than
        int dimension = tokenizer.countTokens() - 1;   // the dimension
        // if dimension is <1, there has to be an error:
        if (dimension < 1) {
            throw new Exception("File has less than one dimension.");   // notify user
        }
        r.close();
        return dimension;
    }

    /**
     * computeSolLength
     * compute le solution length : numbers of lines in the sol file
     * @param File
     * @return
     */
    public static int computeSolLength(String file) throws FileNotFoundException, IOException {
        /* get length of solution file */
        boolean eof = false;                        // whether it is end of file or not
        int solLength = 0;                          // length of solution array to be calculated
        FileReader r = new FileReader(file);        // initialize reader and
        BufferedReader i1 = new BufferedReader(r);  // buffered reader
        // keep looping until end of file
        while (!eof) {
            // read addedLines line, if it's not null
            if (i1.readLine() != null) {
                solLength++;// (which means not at eof), count it
            // else it is eof, close the reader and halt the loop
            } else {
                r.close();
                eof = true;
            }
        }
        return solLength;
    }
}
